package com.gitee.huanminabc.jlambda_sql.jdbc;

import com.gitee.huanminabc.jcommon.exception.CommonException;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Map;

/**
 * @description:
 * @author: huanmin
 * @create: 2025-04-10 10:10
 **/
public class JdbcManage {
    protected static final ThreadLocal<String> dbKey = new ThreadLocal<>();
    private static String defaultDbKey = null;

    public static void setDefaultDbKey(String dbKey) {
        JdbcManage.defaultDbKey = dbKey;
        toggleDbKey(dbKey);
    }
    //设置和切换当前数据源
    public static void toggleDbKey(String dbKey) {
        JdbcManage.dbKey.set(dbKey);
    }

    //获取当前数据源的key
    public static String getDbKey() {
        String dbKey = JdbcManage.dbKey.get();
        if (dbKey == null) {
            dbKey = defaultDbKey;
        }
        return dbKey;
    }

    //获取当前数据源
    public static DataSource getDataSource() {
        String dbKey = getDbKey();
        if (dbKey == null) {
            throw new CommonException("No data source key set");
        }
        return JdbcDataSource.getDataSource(dbKey);
    }





    public static void connectionClose(Connection connection) {
        try {
            //如果没有开启事物就关闭连接
            if (!TransactionManage.isTransaction()) {
                connection.close();
            }
        } catch (SQLException e) {
            throw new CommonException(e, "Error closing connection");
        }
    }

    //线程关闭前需要释放jdbc的上下文
    public static void clear() {
        Map<String, Connection> stringConnectionMap = TransactionManage.transactionConnectionManage.get();
        if (stringConnectionMap != null) {
            stringConnectionMap.forEach((key, connection) -> {
                if (connection != null) {
                    try {
                        connection.close();
                    } catch (SQLException e) {
                        throw new CommonException(e, "Error closing connection");
                    }
                }
            });
            TransactionManage.transactionConnectionManage.remove();
        }
        TransactionManage.transactionKey.remove();
        JdbcManage.dbKey.remove();
    }
}
